﻿using System;

namespace CustomerContactSystem.WebForms.Enquiries.Customers {
    public partial class Email : BasePage {
        protected void Page_Load(object sender, EventArgs e) {
            if (!IsValidPageRequest(true, true, "id")) {
                return;
            }

            EnquiryIdCaption.Text = Request.QueryString["id"];
            EnquiryIdCaption.NavigateUrl = "~/Enquiries/View.aspx?id=" + Request.QueryString["id"];
            GetDefaultEmailDetails();
        }

        private void GetDefaultEmailDetails() {
            var enquiryId = int.Parse(Request.QueryString["id"]);
            var enquiry = EnquiryRepository.GetById(enquiryId);

            if (enquiry == null || enquiry.Customer == null) {
                return;
            }

            EmailFrom.Text = ConfigSettings.OrganisationPublicEmail;
            if (string.IsNullOrEmpty(EmailFrom.Text)) {
                EmailFrom.Text = LoggedUser.Email;
            }

            EmailTo.Text = enquiry.Customer.Email;
            EmailSubject.Text = "Enquiry Received " + enquiry.DateOfEnquiry.ToShortDateString();
            
            if (enquiry.FixYourStreetId > 0) {
                EmailContent.Text = "Enquiry (http://www.fixyourstreet.ie/reports/view/" + enquiry.FixYourStreetId + "):";
            }
            else {
                EmailContent.Text = "Enquiry:";
            }
            EmailContent.Text += "\n\n";
            EmailContent.Text += enquiry.EnquiryDetail.Replace("<br />","\n");
        }

        protected void SubmitEmailClick(object sender, EventArgs e) {
            if (!IsValidPageRequest(true, false, "id")) {
                return;
            }

            var enquiryId = int.Parse(Request.QueryString["id"]);
            var enquiry = EnquiryRepository.GetById(enquiryId);

            if (enquiry == null || enquiry.Customer == null) {
                return;
            }

            var customerEmail = enquiry.EmailCustomer(EmailContent.Text.Replace("\n", "<br />"), EmailFrom.Text,
                                                      EmailTo.Text, EmailSubject.Text, LoggedUser.DisplayName);

            if (!IsValidObject(customerEmail, SubmitEmailResultMessage)) {
                return;
            }

            EnquiryRepository.Update(enquiry);

            Response.Redirect("~/Enquiries/View.aspx?id=" + enquiry.Id);
        }
    }
}